package cn.entergx.smallmengplan

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.Toast
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.contract.ActivityResultContract
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import cn.entergx.smallmengplan.delegate.SimpleDelegateAdapter
import cn.entergx.smallmengplan.network.Repo
import cn.entergx.yztx.bean.page.SpringPage
import com.alibaba.android.vlayout.DelegateAdapter
import com.alibaba.android.vlayout.VirtualLayoutManager
import com.alibaba.android.vlayout.layout.LinearLayoutHelper
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.xuexiang.xui.adapter.recyclerview.RecyclerViewHolder
import com.xuexiang.xui.widget.actionbar.TitleBar.ImageAction
import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog.SingleButtonCallback
import com.yanzhenjie.recyclerview.*
import kotlinx.android.synthetic.main.activity_list.*
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.item_community_post.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class ListActivity : AppCompatActivity() {
    private var page = 0
    private lateinit var recyclerView: SwipeRecyclerView
    private lateinit var refreshLayout: SmartRefreshLayout
    private lateinit var mNewsAdapter: SimpleDelegateAdapter<LoveEvent>
    private var mDelegateAdapter: DelegateAdapter? = null
    private val mAdapters: MutableList<DelegateAdapter.Adapter<*>> =
        ArrayList()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_list)
        titlebar.setLeftClickListener {
            finish()
        }.addAction(object : ImageAction(R.drawable.ic_add_white_24dp) {
            override fun performAction(view: View) {
                startActivityForResult(Intent(this@ListActivity, WriteActivity::class.java),0)
            }
        })
        initViews()
        initListeners()
    }

    private fun initViews() {
        recyclerView = rv_v
        refreshLayout = rf_v
        //必须在setAdapter之前调用
        recyclerView.setSwipeMenuCreator(swipeMenuCreator)
        //必须在setAdapter之前调用
        recyclerView.setOnItemMenuClickListener(mMenuItemClickListener)
        // 1.设置VirtualLayoutManager
        val virtualLayoutManager = VirtualLayoutManager(this)
        recyclerView.layoutManager = virtualLayoutManager

        // 2.设置RecycledViews复用池大小（可选）
        val viewPool = RecyclerView.RecycledViewPool()
        viewPool.setMaxRecycledViews(0, 20)
        recyclerView.setRecycledViewPool(viewPool)


        //资讯，线性布局
        mNewsAdapter = object : SimpleDelegateAdapter<LoveEvent>(
            R.layout.item_community_post,
            LinearLayoutHelper()
        ) {
            override fun bindData(
                holder: RecyclerViewHolder,
                position: Int,
                model: LoveEvent?
            ) {
//                holder.text(R.id.tv_comment_count_LoveEvent,model?.comment_count?.toString())
//                holder.text(R.id.tv_like_count_LoveEvent,model?.like_count?.toString())
//                holder.text(R.id.tv_view_count_LoveEvent,"${model?.view_count}阅读")
//                holder.image(R.id.ri_avatar_community,model?.user?.avatar_url)
//                holder.text(R.id.tv_community_up_name, model?.user?.user_name)
//                holder.text(R.id.tv_community_LoveEvent_title, model?.LoveEvent_name)
//                holder.text(R.id.tv_community_LoveEvent_des, model?.LoveEvent_content)
//                holder.click(
//                    R.id.card_view
//                ) { v: View? ->
//                    startActivity(Intent(requireContext(),LoveEventActivity::class.java).also { it.putExtra("LoveEvent",model) })
//                }
                holder.click(R.id.iv_note) {
                    model?.note?.let { it1 -> showInputDialog(it1) }
                }
                if (model?.completed == 1)
                    holder.image(R.id.iv_completed, R.drawable.c)
                else
                    holder.findViewById<ImageView>(R.id.iv_completed).setImageDrawable(null)
                holder.text(R.id.tv_content, model?.content)
            }
        }
        mDelegateAdapter = DelegateAdapter(virtualLayoutManager)
        //mAdapters.add(floatAdapter)
        //mAdapters.add(scrollFixAdapter)
        //mAdapters.add(commonAdapter)
        //mAdapters.add(titleAdapter)
        mAdapters.add(mNewsAdapter)

        // 3.设置DelegateAdapter
        recyclerView.adapter = mDelegateAdapter
    }

    /**
     * 带输入框的对话框
     */
    private fun showInputDialog(note: String) {
        MaterialDialog.Builder(this)
            .content(note)
            .positiveText("确定")
            .onPositive(SingleButtonCallback { dialog: MaterialDialog, which: DialogAction? ->
//                //XToastUtils.toast(
//                    "你输入了:" + dialog.getInputEditText()!!
//                        .getText().toString()
//                )
            })
            .cancelable(false)
            .show()
    }

    /**
     * 菜单创建器，在Item要创建菜单的时候调用。
     */
    private val swipeMenuCreator =
        SwipeMenuCreator { swipeLeftMenu: SwipeMenu, swipeRightMenu: SwipeMenu, position: Int ->
            val width = 70

            // 1. MATCH_PARENT 自适应高度，保持和Item一样高;
            // 2. 指定具体的高，比如80;
            // 3. WRAP_CONTENT，自身高度，不推荐;
            val height = ViewGroup.LayoutParams.MATCH_PARENT
            // 添加右侧的，如果不添加，则右侧不会出现菜单。
            val deleteItem: SwipeMenuItem =
                SwipeMenuItem(this)
                    .setBackgroundColor(Color.RED)
                    .setText("删除")
                    .setTextColor(Color.WHITE)
                    .setWidth(width)
                    .setHeight(height)
            val editItem: SwipeMenuItem =
                SwipeMenuItem(this)
                    .setBackgroundColor(Color.GREEN)
                    .setText("编辑")
                    .setTextColor(Color.WHITE)
                    .setWidth(width)
                    .setHeight(height)
            swipeRightMenu.addMenuItem(editItem)
            swipeRightMenu.addMenuItem(deleteItem) // 添加菜单到右侧。
        }

    /**
     * RecyclerView的Item的Menu点击监听。
     */
    private val mMenuItemClickListener =
        OnItemMenuClickListener { menuBridge: SwipeMenuBridge, p: Int ->
            menuBridge.closeMenu()
            val direction = menuBridge.direction // 左侧还是右侧菜单。
            val menuPosition = menuBridge.position // 菜单在RecyclerView的Item中的Position。
            if (direction == SwipeRecyclerView.RIGHT_DIRECTION) {
                //XToastUtils.toast("list第$position; 右侧菜单第$menuPosition")
                if (menuPosition == 0) {
//                    startActivity(Intent(this, WriteActivity::class.java).also {
//                        it.putExtra("LoveEvent", mNewsAdapter.getItem(p))
//                    })
                    startActivityForResult(Intent(this@ListActivity, WriteActivity::class.java).also {
                        it.putExtra("LoveEvent", mNewsAdapter.getItem(p))
                    },0)
                }else{
                    delete(p)
                }
            } else if (direction == SwipeRecyclerView.LEFT_DIRECTION) {
                //XToastUtils.toast("list第$position; 左侧菜单第$menuPosition")
            }
        }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode==0)
            initData(0)
        //Toast.makeText(this, "11 $resultCode", Toast.LENGTH_SHORT).show()
    }
    private fun delete(p: Int) {
        Repo.delete(mNewsAdapter.getItem(p).id,object :Callback<Int>{
            override fun onResponse(call: Call<Int>, response: Response<Int>) {
                if (response.body() == 0) {
                    Toast.makeText(this@ListActivity, "删除成功", Toast.LENGTH_SHORT).show()
                    initData(0)
                }else{
                    Toast.makeText(this@ListActivity, "删除失败", Toast.LENGTH_SHORT).show()
                }
            }

            override fun onFailure(call: Call<Int>, t: Throwable) {
                Toast.makeText(this@ListActivity, "删除失败", Toast.LENGTH_SHORT).show()
            }
        })
    }

    private fun initListeners() {
        //下拉刷新
        refreshLayout.setOnRefreshListener {
            initData(0)
        }
        //上拉加载
        refreshLayout.setOnLoadMoreListener {
            initData(page)
        }
        refreshLayout.autoRefresh() //第一次进入触发自动刷新，演示效果
        //initData(0)
    }

    private fun initData(page: Int) {
        if (page == 0) this.page = 0
        this.page += 1
        Repo.get(page, 30, object : Callback<SpringPage<LoveEvent>> {
            override fun onFailure(call: Call<SpringPage<LoveEvent>>, t: Throwable) {
                //Utils.toast("获取贴子失败:请求异常")
                if (page == 0) {
                    mDelegateAdapter!!.setAdapters(mAdapters)
                    refreshLayout.finishRefresh()
                } else {
                    refreshLayout.finishLoadMore()
                }
                println(t)
            }

            override fun onResponse(
                call: Call<SpringPage<LoveEvent>>,
                response: Response<SpringPage<LoveEvent>>
            ) {
                println(response.body()?.content)
                if (page == 0) {
                    mNewsAdapter.refresh(response.body()!!.content)
                    mDelegateAdapter!!.setAdapters(mAdapters)
                } else {
                    if (response.body()!!.empty) {
                        this@ListActivity.page -= 1
                        //Utils.toast("已全部加载")
                        refreshLayout.finishLoadMoreWithNoMoreData()
                    } else mNewsAdapter.loadMore(response.body()!!.content)
                }
                if (page == 0)
                    refreshLayout.finishRefresh()
                else
                    refreshLayout.finishLoadMore()
            }
        })
    }
}